package com.example.ssm.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 登录认证的控制器
 *
 * @author yaojianfeng
 */
@Controller
@RequestMapping("/sys")
public class LoginController {



    @RequestMapping(value = "/login-success",produces = "application/json;charset=utf-8")
    public String loginSuccess() {
        return "loginSuccess";
    }

    @RequestMapping(value = "/welcome")
    public String welcomeAdmin(ModelMap model) {
        return "index";
    }

    @RequestMapping(value = "/r1",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String getR1(){
        return getUserDetails().getUsername() + "访问r1资源";
    }
    @RequestMapping(value = "/r2",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String getR2(){
        return getUserDetails().getUsername()+ "访问r2资源";
    }

    @RequestMapping(value = "/r3", produces = "application/json;charset=utf-8")
    @ResponseBody
    @PreAuthorize("hasAuthority('p3')")
    public String getR3() {
        return getUserDetails().getUsername() + "访问r3资源";
    }


    /**
     * 从会话信息中获取当前用户
     * @return
     */
    private UserDetails  getUserDetails(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            Object details = authentication.getPrincipal();
            if (details instanceof org.springframework.security.core.userdetails.UserDetails){
                return (UserDetails) details;
            }
        }
        return User.withUsername("匿名").build();
    }
}
